import { ipcMain, dialog } from 'electron';
import { getVideoInfo } from '../ffmpeg/base';
import { convertVideo } from '../ffmpeg/converter';
import { compressVideo, compressToTargetSize } from '../ffmpeg/compressor';
import { separateAudioVideo } from '../ffmpeg/separator';
import { addImageWatermark, addTextWatermark, removeWatermark } from '../ffmpeg/watermark';
import { concatVideos, splitVideo } from '../ffmpeg/editor';

// 任务管理
const activeTasks = new Map();

/**
 * 设置所有 FFmpeg 相关的 IPC 处理器
 */
export function setupFFmpegHandlers() {
  // 获取视频信息
  ipcMain.handle('ffmpeg:get-info', async (_event, filePath: string) => {
    try {
      const info = await getVideoInfo(filePath);
      return { success: true, data: info };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  });

  // 视频格式转换
  ipcMain.handle('ffmpeg:convert', async (event, options: any) => {
    const taskId = Date.now().toString();
    try {
      const task = convertVideo(options);
      activeTasks.set(taskId, task);

      // 监听进度并发送到渲染进程
      task.on('progress', (data) => {
        event.sender.send('ffmpeg:progress', { taskId, ...data });
      });

      await task.start();
      activeTasks.delete(taskId);

      return { success: true, taskId };
    } catch (error: any) {
      activeTasks.delete(taskId);
      return { success: false, error: error.message };
    }
  });

  // 视频压缩
  ipcMain.handle('ffmpeg:compress', async (event, options: any) => {
    const taskId = Date.now().toString();
    try {
      let task;

      if (options.targetSize) {
        // 按目标大小压缩
        const info = await getVideoInfo(options.input);
        task = compressToTargetSize(options.input, options.output, options.targetSize, info.duration);
      } else {
        // 普通压缩
        task = compressVideo(options);
      }

      activeTasks.set(taskId, task);

      task.on('progress', (data) => {
        event.sender.send('ffmpeg:progress', { taskId, ...data });
      });

      await task.start();
      activeTasks.delete(taskId);

      return { success: true, taskId };
    } catch (error: any) {
      activeTasks.delete(taskId);
      return { success: false, error: error.message };
    }
  });

  // 音视频分离
  ipcMain.handle('ffmpeg:separate', async (_event, options: any) => {
    const taskId = Date.now().toString();
    try {
      await separateAudioVideo(options);
      return { success: true, taskId };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  });

  // 去除水印
  ipcMain.handle('ffmpeg:remove-watermark', async (event, options: any) => {
    const taskId = Date.now().toString();
    try {
      const task = removeWatermark(options);
      activeTasks.set(taskId, task);

      task.on('progress', (data) => {
        event.sender.send('ffmpeg:progress', { taskId, ...data });
      });

      await task.start();
      activeTasks.delete(taskId);

      return { success: true, taskId };
    } catch (error: any) {
      activeTasks.delete(taskId);
      return { success: false, error: error.message };
    }
  });

  // 添加水印
  ipcMain.handle('ffmpeg:add-watermark', async (event, options: any) => {
    const taskId = Date.now().toString();
    try {
      const task = options.type === 'text' ? addTextWatermark(options) : addImageWatermark(options);

      activeTasks.set(taskId, task);

      task.on('progress', (data) => {
        event.sender.send('ffmpeg:progress', { taskId, ...data });
      });

      await task.start();
      activeTasks.delete(taskId);

      return { success: true, taskId };
    } catch (error: any) {
      activeTasks.delete(taskId);
      return { success: false, error: error.message };
    }
  });

  // 视频拼接
  ipcMain.handle('ffmpeg:concat', async (event, options: any) => {
    const taskId = Date.now().toString();
    try {
      const task = concatVideos(options);
      activeTasks.set(taskId, task);

      task.on('progress', (data) => {
        event.sender.send('ffmpeg:progress', { taskId, ...data });
      });

      await task.start();
      activeTasks.delete(taskId);

      return { success: true, taskId };
    } catch (error: any) {
      activeTasks.delete(taskId);
      return { success: false, error: error.message };
    }
  });

  // 视频分割
  ipcMain.handle('ffmpeg:split', async (event, options: any) => {
    const taskId = Date.now().toString();
    try {
      const task = splitVideo(options);
      activeTasks.set(taskId, task);

      task.on('progress', (data) => {
        event.sender.send('ffmpeg:progress', { taskId, ...data });
      });

      await task.start();
      activeTasks.delete(taskId);

      return { success: true, taskId };
    } catch (error: any) {
      activeTasks.delete(taskId);
      return { success: false, error: error.message };
    }
  });

  // 取消任务
  ipcMain.handle('ffmpeg:cancel', (_event, taskId: string) => {
    const task = activeTasks.get(taskId);
    if (task) {
      task.cancel();
      activeTasks.delete(taskId);
      return { success: true };
    }
    return { success: false, error: 'Task not found' };
  });

  // 文件对话框 - 打开文件
  ipcMain.handle('dialog:open-file', async (_event, options: any) => {
    const result = await dialog.showOpenDialog(options);
    return result;
  });

  // 文件对话框 - 保存文件
  ipcMain.handle('dialog:save-file', async (_event, options: any) => {
    const result = await dialog.showSaveDialog(options);
    return result;
  });
}
